package com.example.library.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;


public class Libinterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("进入拦截器了");
        HttpSession session =request.getSession(false);

        if(session!=null&&session.getAttribute("username")!=null){
            System.out.println("true");
            return true;
        }else{
            //如果用户未登录
            //重定向到登录页面
            System.out.println("重定向到登录页面");
            PrintWriter printWriter= response.getWriter();
            printWriter.write("{code:0,message:\"not login!\"}");
            response.sendRedirect("/library/tologin");
            return false;
        }

    }
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
    }
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
    }
}